package com.itheima.pinda.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.pinda.DTO.transportline.TransportTripsTruckDriverDto;
import com.itheima.pinda.common.utils.Result;
import com.itheima.pinda.entity.transportline.PdTransportTripsTruckDriver;
import com.itheima.pinda.mapper.PdTransportTripsTruckDriverMapper;
import com.itheima.pinda.mapstruct.TransportDTO2Entity;
import com.itheima.pinda.service.PdTransportTripsTruckDriverService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PdTransportTripsTruckDriverServiceImpl extends ServiceImpl<PdTransportTripsTruckDriverMapper, PdTransportTripsTruckDriver> implements PdTransportTripsTruckDriverService {

    @Resource
    private TransportDTO2Entity dto2Entity;


    /**
     * 批量保存车次与车辆和司机关联关系
     *
     * @param transportTripsId 线路类型id
     * @param dtoList          车次与车辆和司机关联关系
     * @return 返回信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result batchSaveTruckDriver(String transportTripsId, List<TransportTripsTruckDriverDto> dtoList) {
        // 查出操作前关系列表
        List<PdTransportTripsTruckDriver> befTripsTruckDriverList = super.list(Wrappers.<PdTransportTripsTruckDriver>lambdaQuery()
                .eq(PdTransportTripsTruckDriver::getTransportTripsId, transportTripsId));

        Map<String, PdTransportTripsTruckDriver> sourceTruckMap = new HashMap<>();
        befTripsTruckDriverList.forEach(tripsTruckDriver ->
                sourceTruckMap.put(tripsTruckDriver.getTransportTripsId() + "_" + tripsTruckDriver.getUserId(), tripsTruckDriver));

        // 清除旧的关联关系
        super.remove(Wrappers.<PdTransportTripsTruckDriver>lambdaQuery()
                .eq(PdTransportTripsTruckDriver::getTransportTripsId, transportTripsId));
        List<PdTransportTripsTruckDriver> saveList = new ArrayList<>();

        // 遍历新传入数据
        dtoList.forEach(tripsTruckDriverDto -> {
            PdTransportTripsTruckDriver saveData = dto2Entity.conver(tripsTruckDriverDto);
            String key = tripsTruckDriverDto.getTransportTripsId() + "_" + tripsTruckDriverDto.getUserId();
            if (sourceTruckMap.containsKey(key)) {
                PdTransportTripsTruckDriver source = sourceTruckMap.get(key);
                if (saveData.getUserId() == null) {
                    saveData.setUserId(source.getUserId());
                }
            }
            saveList.add(saveData);
        });
        boolean res = super.saveBatch(saveList);

        return res ? Result.ok() : Result.error("批量保存失败!, 请联系管理员");
    }

    /**
     * 获取车次与车辆和司机关联关系列表
     *
     * @param transportTripsId 车次id
     * @param truckId          车辆id
     * @param userId           司机id
     * @return 车次与车辆和司机关联关系列表
     */
    @Override
    public List<TransportTripsTruckDriverDto> findAllTruckDriverTransportTrips(String transportTripsId, String truckId, String userId) {
        List<PdTransportTripsTruckDriver> pdTransportTripsTruckDriverList = super.list(Wrappers.<PdTransportTripsTruckDriver>lambdaQuery()
                .eq(StringUtils.isNotBlank(transportTripsId), PdTransportTripsTruckDriver::getTransportTripsId, transportTripsId)
                .eq(StringUtils.isNotBlank(truckId), PdTransportTripsTruckDriver::getTruckId, truckId)
                .eq(StringUtils.isNotBlank(userId), PdTransportTripsTruckDriver::getUserId, userId));

        return pdTransportTripsTruckDriverList.stream()
                .map(item -> dto2Entity.conver(item))
                .collect(Collectors.toList());
    }
}
